import { ServeStaticModule } from '@nestjs/serve-static'
import { join } from 'node:path'
import { Module } from '@nestjs/common'
import { ElectronModule } from '@doubleshot/nest-electron'
import { TypeOrmModule } from '@nestjs/typeorm'
import { BrowserWindow, app } from 'electron'
import { setupIpcMainHander } from './ipcHandler'
import ProjectEntity from '@main/db/entity/ProjectEntity'
import { ProjectController } from '@main/controller/ProjectController'
import { ProjectService } from './service/ProjectService'
import { ModuleMetadata } from '@nestjs/common/interfaces/modules/module-metadata.interface'
import { readConfig } from '@main/util/CommUtil'
import { ApiController } from '@main/controller/ApiController'
import { ApiService } from '@main/service/ApiService'
import ApiEntity from './db/entity/ApiEntity'
import { MockController } from './controller/MockController'
import { APP_FILTER, APP_INTERCEPTOR } from '@nestjs/core'
import { BizExceptionFilter } from './filter/BizExceptionFilter'
import { mutilWindowInstance } from './window/MutilWindow'

const configObj = readConfig()
console.log('配置文件信息', configObj)

const moduleImports: ModuleMetadata['imports'] = [
  ElectronModule.registerAsync({
    useFactory: async () => {
      const isDev = !app.isPackaged
      const win = new BrowserWindow({
        width: 1024,
        height: 768,
        autoHideMenuBar: true,
        webPreferences: {
          contextIsolation: true,
          preload: join(__dirname, '../preload/index.js'),
        },
      })

      if (isDev) {
        // 开发环境自动打开开发者工具
        win.webContents.openDevTools()
      } else {
        // 打包后去掉菜单栏
        win.setMenu(null)
      }
      setupIpcMainHander(configObj.httpServer.port)

      win.on('closed', () => {
        // 销毁所有多窗口，防止electron进程无法彻底销毁
        mutilWindowInstance.destroyAll()
        win.destroy()
      })

      const URL = isDev ? process.env.DS_RENDERER_URL : `file://${join(app.getAppPath(), 'dist/render/index.html')}`

      win.loadURL(URL)

      return { win }
    },
  }),
  TypeOrmModule.forFeature([ProjectEntity, ApiEntity]),
  TypeOrmModule.forRoot({
    type: 'better-sqlite3',
    database: './mydb.db',
    // entities: [ProjectEntity],
    entities: [join(__dirname, '**', '*.{js,ts}'), join('src', 'main', 'db', 'entry', '*.{js,ts}')],
    // 打印原始sql语句
    logging: true,
    // 使实体定义与数据同步(自动建表)
    synchronize: true,
    autoLoadEntities: true,
    extra: {
      timezone: 'Asia/Shanghai', // 设置时区为中国
      useUTC: true,
    },
  }),
]

// moduleImports.push(
//   ServeStaticModule.forRoot({
//     rootPath: join('swagger-ui'),
//     serveRoot: '/static-swagger-ui', // 需要添加'/' 此处相当于添加前缀
//   })
// )
@Module({
  imports: moduleImports,
  controllers: [MockController, ProjectController, ApiController],
  providers: [
    {
      provide: APP_FILTER,
      useClass: BizExceptionFilter,
    },
    ProjectService,
    ApiService,
  ],
})
export class AppModule {}
